package com.activititest.service.impl;

import com.activititest.service.AdminACServer;
import org.activiti.engine.*;
import org.activiti.engine.identity.Group;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AdminACServerImpl implements AdminACServer {
    private Logger logger = LoggerFactory.getLogger(ActivitiServiceImpl.class);
    private static final String PROCESS_DEFINE_KEY = "yingji";
    private static final String ADMINUSER = "adminuser";
    @Resource
    private RuntimeService runtimeService;
    @Resource
    private IdentityService identityService;
    @Resource
    private TaskService taskService;
    @Resource
    private HistoryService historyService;
    @Resource
    private RepositoryService repositoryService;

    @Override
    public String publishTask(String area, List<String> pollutant_ids) {
        String taskId2;
        try{
            identityService.setAuthenticatedUserId(ADMINUSER);
            // 开始流程
            ProcessInstance pi = runtimeService.startProcessInstanceByKey(PROCESS_DEFINE_KEY);
            String processId = pi.getId();
            logger.info("===============processId==================="+processId);

            // 查询当前任务
            Task currentTask = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
            String taskId1 = currentTask.getId();
            logger.info("===============taskId1==================="+taskId1);

            // 申明任务人
            //taskService.claim(currentTask.getId(), userName);
            taskService.setAssignee(taskId1, ADMINUSER);
//            Map<String, Object> vars = new HashMap<>(4);
//            vars.put("applyUser", userName);
//            vars.put("days", vac.getDays());
//            vars.put("reason", vac.getReason());
            //在此方法中，Vaction 是申请时的具体信息，在完成“申请请假”任务时，可以将这些信息设置成参数。
            //完成第一步申请
            taskService.complete(currentTask.getId());

            // 到了下一个任务， 应该在此处指派任务由谁来处理
            // 重新获取当前任务

            Task task = taskService.createTaskQuery().processInstanceId(processId).singleResult();
             taskId2 = task.getId();
            logger.info("===============taskId2==================="+taskId2+task.getName());

            //taskService.setAssignee(taskId2, area);
            //Group group = identityService.createGroupQuery().groupName(area).singleResult();
            taskService.addCandidateGroup(taskId2,area);

        }catch (Exception e){
            e.printStackTrace();
            return "null";
        }
        return taskId2;
    }
}
